import 'dart:convert';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class HkAdverSwiper extends StatefulWidget {
  ///app名称
  final String appName;

  ///页面名称
  final String pageSelect;

  ///位置标识
  final String arrange;

  ///app版本名称
  final String version;

  ///请求baseUrl
  final String requestBaseUrl;

  ///广告接口名称
  final String requestUrl;

  final Function(String jumpLink, String index) onItemClick;

  static

      /// default auto play delay
      const int kDefaultAutoplayDelayMs = 3000;

  static

      ///  Default auto play transition duration (in millisecond)
      const int kDefaultAutoplayTransactionDuration = 300;

  ///Duration of the animation between transactions (in millisecond).
  final int autoplayDelay;

  ///auto play transition duration (in millisecond)
  final int duration;

  //控制是否自动轮播
  final bool isAutoPlay;

  HkAdverSwiper({
    @required this.appName,
    @required this.pageSelect,
    this.arrange: "",
    @required this.version,
    @required this.onItemClick,
    this.requestBaseUrl: 'http://119.61.26.55:8140/p4-ref-pt/',
    this.requestUrl: 'getAdverToApp?',
    this.duration: kDefaultAutoplayTransactionDuration,
    this.autoplayDelay: kDefaultAutoplayDelayMs,
    this.isAutoPlay: true,
  });
  @override
  _HkAdverSwiperState createState() => _HkAdverSwiperState();
}

class _HkAdverSwiperState extends State<HkAdverSwiper> {
  /// 刷新支付首页annange = 1 的轮播图数据列表
  List<dynamic> _sXZFSY1ListData = [];

  /// 刷新支付首页annange = 2 的轮播图数据列表
  List<dynamic> _sXZFSY2ListData = [];

  /// 刷新支付返现页面轮播图数据列表
  List<dynamic> _sXZFFXListData = [];

  bool hasData = false;

  @override
  void initState() {
    super.initState();
    requestData();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: hasData
          ? Swiper(
              duration: widget.duration,
              autoplayDelay: widget.autoplayDelay,
              itemBuilder: (BuildContext context, int index) {
                return _swiperCell(index);
              },
              itemCount: _swiperItemCount(),
              pagination: _swiperPagination(),
              scrollDirection: Axis.horizontal,
              autoplay: hasData && widget.isAutoPlay,
            )
          : _defaultSwiperCell(),
    );
  }

  ///请求轮播图数据
  void requestData() async {
    Dio dio = new Dio();
    dio.options.baseUrl = widget.requestBaseUrl;
    FormData formData = new FormData.fromMap({
      'appName': widget.appName,
      'pageSelect': widget.pageSelect,
      'arrange': widget.arrange,
      'version': widget.version,
      'platform': Platform.isAndroid ? 'Android' : 'iOS',
    });
    Response response = await dio.post(widget.requestUrl, data: formData);
    print('当前appName:' + widget.appName);
    print('当前app版本:' + widget.version);
    print('当前平台:${Platform.isAndroid ? 'Android' : 'iOS'}');
    print('当前page:' + widget.pageSelect);
    print('当前arrange:' + widget.arrange);
    print('轮播图返回数据：' + response.data.toString());
    Map<String, dynamic> data = json.decode(response.data);
    print("map.code=" + data['code']);
    if ('1' == data['code']) {
      if (widget.appName == 'SXZF') {
        if (widget.pageSelect == 'SY' && widget.arrange == '1') {
          dealSXZFSY1Data(data);
        } else if (widget.pageSelect == 'SY' && widget.arrange == '2') {
          dealSXZFSY2Data(data);
        } else if (widget.pageSelect == 'FX') {
          dealSXZFFXData(data);
        }
      }
    }
  }

  ///轮播图item布局
  Widget _swiperCell(index) {
    if (widget.appName == 'SXZF') {
      if (widget.pageSelect == 'SY' && widget.arrange == '1') {
        //刷新支付首页annange = 1 的轮播图item布局
        return _sXZFSY1SwiperCell(index);
      } else if (widget.pageSelect == 'SY' && widget.arrange == '2') {
        //刷新支付首页annange = 2 的轮播图item布局
        return _sXZFSY2SwiperCell(index);
      } else if (widget.pageSelect == 'FX') {
        //刷新支付返现轮播图item布局
        return _sXZFFXSwiperCell(index);
      }
    }
  }

  ///刷新支付首页annange = 1 的轮播图的分页指引
  Widget swiperPagination(BuildContext context, SwiperPluginConfig config) {
    List<Widget> _children = [];
    for (int i = 0; i < config.itemCount; i++) {
      _children.add(Container(
        decoration: BoxDecoration(
          color:
              config.activeIndex == i ? Color(0xff6a80ff) : Color(0xfff1f1f1),
          borderRadius: BorderRadius.all(Radius.circular(2)),
        ),
        width: 20,
        height: 4,
      ));
    }
    return Container(
      margin: EdgeInsets.only(bottom: 0),
      alignment: Alignment.bottomCenter,
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xfff1f1f1),
          borderRadius: BorderRadius.all(Radius.circular(2)),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: _children,
        ),
      ),
    );
  }

  ///刷新支付首页annange = 1 的轮播图item布局
  Widget _sXZFSY1SwiperCell(index) {
    int newIndex = 2 * index;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        InkWell(
          onTap: () {
            widget.onItemClick(_sXZFSY1ListData[newIndex + 0]['jumpLink'], '1');
          },
          child: Container(
            height: ScreenUtil.getInstance().getHeight(140),
            width: ScreenUtil.getInstance().getWidth(320),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10.0),
              child: loadNetworkImageAdver(
                  _sXZFSY1ListData[newIndex + 0]['materialUrl'],
                  fit: BoxFit.fill,
                  placeholder: 'swiper_none'),
            ),
          ),
        ),
        InkWell(
          onTap: () {
            widget.onItemClick(_sXZFSY1ListData[newIndex + 1]['jumpLink'], '1');
          },
          child: Container(
            height: ScreenUtil.getInstance().getHeight(140),
            width: ScreenUtil.getInstance().getWidth(320),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: loadNetworkImageAdver(
                  _sXZFSY1ListData[newIndex + 1]['materialUrl'],
                  fit: BoxFit.fill,
                  placeholder: 'swiper_none'),
            ),
          ),
        ),
      ],
    );
  }

  ///刷新支付首页annange = 2 的轮播图item布局
  Widget _sXZFSY2SwiperCell(index) {
    return InkWell(
      onTap: () {
        widget.onItemClick(_sXZFSY2ListData[index]['jumpLink'], '1');
      },
      child: Container(
          width: double.infinity,
          height: ScreenUtil.getInstance().getHeight(120),
          child: ClipRRect(
              borderRadius: BorderRadius.circular(50.0),
              child: loadNetworkImageAdver(
                  _sXZFSY2ListData[index]['materialUrl'],
                  fit: BoxFit.fill,
                  placeholder: 'swiper_none'))),
    );
  }

  ///刷新支付返现轮播图item布局
  Widget _sXZFFXSwiperCell(index) {
    return InkWell(
      onTap: () {
        widget.onItemClick(_sXZFFXListData[index]['jumpLink'], '1');
      },
      child: Container(
        width: double.infinity,
        height: ScreenUtil.getInstance().getHeight(70),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(5.0),
          child: loadNetworkImageAdver(
            _sXZFFXListData[index]['materialUrl'],
            fit: BoxFit.fill,
            placeholder: 'swiper_none',
          ),
        ),
      ),
    );
  }

  Widget _defaultSwiperCell() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20),
      height: ScreenUtil.getInstance().getHeight(210),
      width: double.infinity,
      child: loadAssetImageAdver('swiper_none', fit: BoxFit.fill),
    );
  }

  ///处理刷新支付首页annange = 1 的轮播图数据
  void dealSXZFSY1Data(data) {
    List<dynamic> list = data['1'];
    if (list != null || list.length > 0) {
      if (list.length % 2 == 1) {
        int index = 0;
        if (list.length > 2) {
          index = list.length - 2;
        }
        Map dic1 = list[index];
        list.insert(index, dic1);
      }
      setState(() {
        hasData = true;
        _sXZFSY1ListData = list;
      });
    }
  }

  ///处理刷新支付首页annange = 2 的轮播图数据
  void dealSXZFSY2Data(data) {
    _sXZFSY2ListData = data['2'];
    if (_sXZFSY2ListData != null || _sXZFSY2ListData.length > 0) {
      hasData = true;
      setState(() {});
    }
  }

  ///处理刷新支付首页annange = 2 的轮播图数据
  void dealSXZFFXData(data) {
    _sXZFFXListData = data['1'];
    if (_sXZFFXListData != null || _sXZFFXListData.length > 0) {
      hasData = true;
      setState(() {});
    }
  }

  int _swiperItemCount() {
    if (widget.appName == 'SXZF') {
      if (widget.pageSelect == 'SY' && widget.arrange == '1') {
        return _sXZFSY1ListData.length ~/ 2;
      } else if (widget.pageSelect == 'SY' && widget.arrange == '2') {
        return _sXZFSY2ListData.length;
      } else if (widget.pageSelect == 'FX') {
        return _sXZFFXListData.length;
      }
    }

    return 0;
  }

  ///轮播图的分页指引
  SwiperCustomPagination _swiperPagination() {
    if (widget.appName == 'SXZF') {
      if (widget.pageSelect == 'SY' && widget.arrange == '1') {
        return SwiperCustomPagination(
            builder: (BuildContext context, SwiperPluginConfig config) {
          return swiperPagination(context, config);
        });
      } else if (widget.pageSelect == 'SY' && widget.arrange == '2') {
        return null;
      } else if (widget.pageSelect == 'FX') {
        return null;
      }
    }
    return null;
  }
}

/// 加载网络图片
Widget loadNetworkImageAdver(String imageUrl,
    {String placeholder: "none",
    double width,
    double height,
    BoxFit fit: BoxFit.cover}) {
  return CachedNetworkImage(
    imageUrl: imageUrl == null ? "" : imageUrl,
    placeholder: (context, url) => loadAssetImageAdver(placeholder,
        height: height, width: width, fit: fit),
    errorWidget: (context, url, error) => loadAssetImageAdver(placeholder,
        height: height, width: width, fit: fit),
    width: width,
    height: height,
    fit: fit,
  );
}

/// 加载本地资源图片
Widget loadAssetImageAdver(String name,
    {double width, double height, BoxFit fit}) {
  if (name.length > 0) {
    return Image.asset(
      'images/$name.png',
      height: height,
      width: width,
      fit: fit,
    );
  } else {
    return Container(
      height: height,
      width: width,
    );
  }
}
